package com.cf.auth.config;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * OAuth2AuthenticationProcessingFilter  核心过滤器
 * BearerTokenExtractor 默认获取token的解析类
 * 已定义请求头存放token时需要扩展这个类
 * @author ChenFeng
 * @date 2021/12/2 5:50 下午
 * @description
 */
public class SwordTokenExtractor extends BearerTokenExtractor {

    @Override
    public Authentication extract(HttpServletRequest httpServletRequest) {
        /**
         * 支持默认的获取请求头的方式,默认可以从三个地方获取：
         * 1、Parameters里面，key = "access_token"
         * 2、header里面，key = "Authorization"
         * 3、form表单里面，key = "access_token"
         */
        Authentication extract = super.extract(httpServletRequest);
        if (extract == null){
            String tokenValue = extractSwordToken(httpServletRequest);
            if (tokenValue != null) {
                PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(tokenValue, "");
                return authentication;
            }
        }
        return null;
    }

    /**
     * 新增从自定义请求头获取token
     * @param request
     * @return
     */
    private String extractSwordToken(HttpServletRequest request) {
        Enumeration headers = request.getHeaders("Sword-Auth");
        String value;
        do {
            if (!headers.hasMoreElements()) {
                return null;
            }

            value = (String)headers.nextElement();
        } while(!value.toLowerCase().startsWith("Bearer".toLowerCase()));

        return value;
    }


}
